package com.base.pig.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.base.pig.config.CommanConfig;
import com.base.pig.entity.ScAlarmRule;
import com.base.pig.entity.ScDevice;
import com.base.pig.mapper.ScAlarmRuleMapper;
import com.base.pig.util.R;
import com.base.pig.service.ScAlarmRuleService;
import com.base.pig.service.ScDeviceService;
import com.base.pig.service.SysDictItemService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * @ProjectName
 * @Package com.pig4cloud.pig.lab.service.impl
 * @ClassName ScAlarmRoleManagerServiceImpl
 * @Description
 * @Company lab
 * @Author wangw
 * @Date 2020/4/29 0029 17:13
 * @UpdateUser
 * @UpdateDate
 * @UpdateRemark
 * @Version 1.0.0
 */
@Slf4j
@Service
@AllArgsConstructor
public class ScAlarmRuleServiceImpl extends ServiceImpl<ScAlarmRuleMapper, ScAlarmRule> implements ScAlarmRuleService {

    @Autowired
    private SysDictItemService sysDictItemService;

    @Autowired
    private ScDeviceService scDeviceService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private CommanConfig commanConfig;

    @Override
    public R getAlarmRuleList(Map map) {
        QueryWrapper ruleWrapper = new QueryWrapper();
        // ruleWrapper.select("distinct sn");
        // 全量查询
        if (StrUtil.isNotBlank(String.valueOf(map.get("deviceType")))) {
            ruleWrapper.eq("device_type", String.valueOf(map.get("deviceType")));
        }
        if (StrUtil.isNotBlank(String.valueOf(map.get("sn")))) {
            ruleWrapper.like("sn", String.valueOf(String.valueOf(map.get("sn"))));
        }
        if (StrUtil.isNotBlank(String.valueOf(map.get("fieldsValue")))) {
            ruleWrapper.eq("fields_value", String.valueOf(map.get("fieldsValue")));
        }
        // 分页条件校验及排序
        Page page = new Page();
        if (map.get("size") != null && !"".equals(map.get("size"))) {
            page.setSize(Long.valueOf(map.get("size").toString()));
        }
        if (map.get("current") != null && !"".equals(map.get("current"))) {
            page.setCurrent(Long.valueOf(map.get("current").toString()));
        }
        List<OrderItem> orders = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        orderItem.setColumn("gmt_create");
        orderItem.setAsc(false);
        orders.add(orderItem);
        page.setOrders(orders);
        IPage iPage = this.page(page, ruleWrapper);
        return R.ok(iPage, "查询成功.");
    }

    @Override
    public R addOrUpdate(ScAlarmRule scAlarmRule) {
        // 参数校验
        if (scAlarmRule.getDeviceType() == null || scAlarmRule.getDeviceType().equals("")) {
            return R.failed(null, "设备类型不能为空.");
        }
        if (scAlarmRule.getSn() == null || scAlarmRule.getSn().equals("")) {
            return R.failed(null, "设备编号不能为空.");
        }
        if (scAlarmRule.getFieldsValue() == null || scAlarmRule.getFieldsValue().equals("")) {
            return R.failed(null, "检测项不能为空.");
        }


        // 设备条件构造器。根据SN码和设备类型查询
        QueryWrapper<ScDevice> deviceSnWrapper = new QueryWrapper();
        deviceSnWrapper.eq("sn", scAlarmRule.getSn());
        deviceSnWrapper.eq("device_type", scAlarmRule.getDeviceType());

        // manufacturerNumber: 厂商编号
        String manufacturerNumber = scDeviceService.getOne(deviceSnWrapper).getManufacturerNumber();
//        String url = "http://192.168.1.30:9080/interface/starwsn/setAlarmRule";
        Map map = new HashMap();
        map.put("sn", scAlarmRule.getSn());
        map.put("manufacturer", manufacturerNumber);
        map.put("lower_limit", scAlarmRule.getLowerLimit());
        map.put("upper_limit", scAlarmRule.getUpperLimit());
        map.put("range", scAlarmRule.getRanges());
        map.put("timeout", scAlarmRule.getTimeout());
        map.put("attribute", scAlarmRule.getFieldsValue());
        transpondUrl(commanConfig.getAlarmRuleUrl(), map);

        // 创建条件构造器，通过SN码和设备厂商查询规则数据是否存在，如果存在，驳回请求，如果不存在，可以入库
        QueryWrapper alarmRuleWrapper = new QueryWrapper();
        alarmRuleWrapper.eq("sn",scAlarmRule.getSn());
        alarmRuleWrapper.eq("device_type",scAlarmRule.getDeviceType());
        alarmRuleWrapper.eq("fields_value",scAlarmRule.getFieldsValue());
        long count = this.count(alarmRuleWrapper);

        if(scAlarmRule.getAlarmId() == null && count > 0){
            return R.failed(false,"该检测项规则已存在.");
        }

        boolean b = this.saveOrUpdate(scAlarmRule);
        if (!b) {
            return R.failed(b, "数据库异常,请联系管理员.");
        }
        return R.ok(b, "更新信息成功!");
    }

    @Async
    public void transpondUrl(String url, Map map) {
        String s= "" ;
        try {
            s = restTemplate.postForObject(url, map,String.class);
        } catch (Exception e) {
            log.error("下发参数异常->{}", s);
        }
    }

    @Override
    public R arrayUpdate(Map map) {
        String ids = map.get("ids").toString();
        JSONArray jsonArray = JSONArray.parseArray(ids);
        if (ids == null || "".equals(ids)) {
            return R.failed(null, "参数为不能为空.");
        }
        String upperLimit = String.valueOf(map.get("upperLimit")); // 报警上限
        String lowerLimit = String.valueOf(map.get("lowerLimit")); // 报警下限
        String ranges = String.valueOf(map.get("ranges")); // 突变范围
        String timeout = String.valueOf(map.get("timeout")); // 超时范围
        List<ScAlarmRule> list = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            ScAlarmRule scAlarmRule = new ScAlarmRule();
            scAlarmRule.setAlarmId(Long.valueOf(jsonArray.get(i).toString()));
            scAlarmRule.setUpperLimit(upperLimit);
            scAlarmRule.setLowerLimit(lowerLimit);
            scAlarmRule.setRanges(ranges);
            scAlarmRule.setTimeout(timeout);
            list.add(scAlarmRule);
        }

        boolean b = this.updateBatchById(list);
        if (!b) {
            return R.failed(null, "批量更新失败.");
        }
        return R.ok(b, "批量更新成功");
    }

    @Override
    public R delete(Map map) {
        if (map.get("ids") == null || "".equals(map.get("ids"))) {
            return R.failed(null, "请求参数为null.");
        }
        String msg = map.get("ids").toString().replaceAll("[\\[\\]]", "");
        String[] array = msg.split(",");
        boolean b = this.removeByIds(Arrays.asList(array));
        if (!b) {
            return R.failed(b, "数据库异常,请联系管理员.");
        }
        return R.ok(b, "删除成功.");
    }

    @Override
    public R getDeviceMonitor() {
        List list = sysDictItemService.getDictChildren("device_type");
        return R.ok(list, "查询完成.");
    }

}
